import os
import subprocess
import shutil
import platform
from PIL import Image, ImageDraw, ImageFont


def create_base_image():
    """创建基础图标图像"""
    size = 1024
    image = Image.new('RGBA', (size, size), (0, 0, 0, 0))
    draw = ImageDraw.Draw(image)
    
    # 绘制圆形背景
    circle_color = (107, 91, 149)  # 紫色背景
    draw.ellipse([0, 0, size, size], fill=circle_color)
    
    # 绘制文字
    text = "RTMP"
    text_color = (255, 255, 255)  # 白色文字
    
    # 计算文字大小和位置
    font_size = size // 3
    try:
        if platform.system() == 'Darwin':
            font = ImageFont.truetype("/System/Library/Fonts/Helvetica.ttc", font_size)
        elif platform.system() == 'Windows':
            font = ImageFont.truetype("arial.ttf", font_size)
        else:
            font = ImageFont.load_default()
    except OSError:
        font = ImageFont.load_default()
    
    # 获取文字大小
    text_bbox = draw.textbbox((0, 0), text, font=font)
    text_width = text_bbox[2] - text_bbox[0]
    text_height = text_bbox[3] - text_bbox[1]
    
    # 计算文字位置（居中）
    x = (size - text_width) // 2
    y = (size - text_height) // 2
    
    # 绘制文字
    draw.text((x, y), text, font=font, fill=text_color)
    
    return image


def create_windows_ico(image):
    """为 Windows 创建 .ico 格式图标"""
    try:
        # Windows 图标尺寸
        sizes = [16, 24, 32, 48, 64, 128, 256]
        icon_images = []
        
        # 创建不同尺寸的图标
        for size in sizes:
            icon_images.append(image.resize((size, size), Image.Resampling.LANCZOS))
        
        # 保存为 .ico 文件
        icon_path = 'app.ico'
        icon_images[0].save(
            icon_path,
            format='ICO',
            sizes=[(s, s) for s in sizes],
            append_images=icon_images[1:]
        )
        print("成功生成 Windows 图标文件: app.ico")
        return True
    except Exception as e:
        print(f"创建 Windows 图标时出错: {str(e)}")
        return False


def create_macos_icns(image):
    """为 macOS 创建 .icns 格式图标"""
    try:
        # 创建临时目录
        iconset_path = 'icons.iconset'
        if os.path.exists(iconset_path):
            shutil.rmtree(iconset_path)
        os.makedirs(iconset_path)
        
        # 创建不同尺寸的图标
        icon_sizes = [16, 32, 64, 128, 256, 512, 1024]
        for s in icon_sizes:
            img = image.resize((s, s), Image.Resampling.LANCZOS)
            img.save(f'{iconset_path}/icon_{s}x{s}.png')
            if s <= 512:  # 创建 @2x 版本
                img = image.resize((s*2, s*2), Image.Resampling.LANCZOS)
                img.save(f'{iconset_path}/icon_{s}x{s}@2x.png')
        
        print("生成 macOS 图标文件...")
        # 使用 iconutil 转换为 icns
        result = subprocess.run(
            ['iconutil', '-c', 'icns', iconset_path],
            capture_output=True,
            text=True
        )
        
        if result.returncode != 0:
            print(f"转换失败: {result.stderr}")
            return False
        
        # 重命名生成的文件
        if os.path.exists('icons.icns'):
            if os.path.exists('app.icns'):
                os.remove('app.icns')
            os.rename('icons.icns', 'app.icns')
            print("成功生成 macOS 图标文件: app.icns")
        
        # 清理临时文件
        shutil.rmtree(iconset_path)
        return True
    except Exception as e:
        print(f"创建 macOS 图标时出错: {str(e)}")
        if os.path.exists(iconset_path):
            shutil.rmtree(iconset_path)
        return False


def create_icon():
    """根据操作系统创建对应格式的图标"""
    try:
        # 创建基础图像
        base_image = create_base_image()
        
        # 根据操作系统创建对应格式的图标
        system = platform.system()
        if system == 'Windows':
            return create_windows_ico(base_image)
        elif system == 'Darwin':
            return create_macos_icns(base_image)
        else:
            print(f"不支持的操作系统: {system}")
            return False
            
    except Exception as e:
        print(f"创建图标时出错: {str(e)}")
        return False


if __name__ == "__main__":
    create_icon() 